import argparse
import subprocess
import sys
import time
import ctypes
import os

from logger import log

subprocess.check_call([sys.executable, "-m", "pip", "install", "pid"])
subprocess.check_call([sys.executable, "-m", "pip", "install", "flask"])
from pid.decorator import pidfile


def hide_console():
    if os.name == 'nt':
        ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)


def monitor_process(command):
    hide_console()
    while True:
        process = subprocess.Popen(command, shell=True)
        process.wait()
        time.sleep(5)  # 间隔一秒重启


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='manual to this script')
    parser.add_argument("--code", type=str, default="lipeng_test")
    parser.add_argument("--host", type=str, default="platform.wechain360.com")
    parser.add_argument("--vs_host", type=str, default="mq.wechain360.com")
    parser.add_argument("--image", type=str, default="False")
    parser.add_argument("--force_codec", type=str, default="")
    parser.add_argument("--ob", type=str, default="False")
    parser.add_argument("--video_client_server", type=str, default="False")
    args = parser.parse_args()

    # Create a decorated version of the function
    decorated_monitor_process = pidfile(pidname=f'webcam_{args.video_client_server}.pid')(monitor_process)

    command = f"python main2.py --code {args.code} --host {args.host} --vs_host {args.vs_host} --ob {args.ob} --image {args.image} --video_client_server {args.video_client_server}"
    if args.force_codec != "":
        command += f" --force_codec {args.force_codec}"
    log.info(command)
    decorated_monitor_process(command)
